<?php
/**
 * Created by PhpStorm.
 * User: zhongyb
 * Date: 2016/6/7
 * Time: 11:30
 */
namespace common\repositories\common;

use common\entities\common\MyscrmBaseproductEntity;
use common\repositories\BaseRepository;
use common\entities\common\MyscrmProductquotaEntity;
use common\support\StringHelper;
use Yii;
use yii\db\ActiveQuery;

class MyscrmProductquotaRepository extends BaseRepository
{

    /**
     * 获得租户级单条记录
     * @param $organizationId
     * @param $baseProductCode
     * @return array|bool
     */
    public function getOrgQuoInfo($organizationId, $baseProductCode = 'SMS')
    {
        $query = new ActiveQuery(MyscrmProductquotaEntity::className());
        return $query->select('a.*')
            ->from(MyscrmProductquotaEntity::tableName() . ' a')
            ->leftJoin('myscrm_baseproduct b', 'a.BaseProductId=b.BaseProductId')
            ->where(['a.OrganizationId' => $organizationId, 'b.BaseProductCode' => $baseProductCode])
            ->andWhere(['ProjectId' => null])
            ->one();
    }

    /**
     * 更新
     * @param $poductQuotaId
     * @param $count
     * @return bool
     */
    public function updateInfo($poductQuotaId, $count)
    {
        /** @var MyscrmProductquotaEntity $entity */
        $entity = MyscrmProductquotaEntity::find()
            ->where(['PoductQuotaId' => $poductQuotaId])
            ->one();
        if ($entity) {
            $entity->Quota = intval($entity->Quota) + $count;
            $entity->save();
            return true;
        }
        return false;
    }

    /**
     * 添加一条记录
     * @param $organizationId
     * @param $count
     * @param string $baseProduct
     * @return bool
     */
    public function addInfo($organizationId, $count, $baseProduct = 'SMS')
    {
        /** @var MyscrmBaseproductEntity $baseProductEntity */
        $baseProductEntity = MyscrmBaseproductEntity::find()
            ->where(['BaseProductCode'=>$baseProduct])
            ->one();
        $productquotaEntity = new MyscrmProductquotaEntity();
        $productquotaEntity->isNewRecord = true;
        $productquotaEntity->PoductQuotaId = StringHelper::uuid();
        $productquotaEntity->BaseProductId = $baseProductEntity->BaseProductId;
        $productquotaEntity->OrganizationId = $organizationId;
        $productquotaEntity->Quota = $count;
        $productquotaEntity->QuotaType = 0;
        $productquotaEntity->UsedNum = 0;

        if($productquotaEntity->save()){
            return true;
        }

        return false;
    }

}